<?php

namespace common\sms\dingdongyun;

use common\sms\SenderInterface;
use common\sms\SenderTrait;

class Sender implements SenderInterface
{
    use SenderTrait;

    private $apiKey;

    private $tpl;

    public function init($config)
    {
        $required = ['api_key', 'tpl'];
        if (!$this->hasKeys($config, $required)) {
            return false;
        }

        $this->apiKey = $config['api_key'];
        $this->tpl = $config['tpl'];
        return true;
    }

    public function checkTemplate($template)
    {
        return true;
    }

    public function send($mobile, $template)
    {
        $this->setErrorMsg('');

        $ch = curl_init();

        /* 设置返回结果为流 */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        /* 设置超时时间*/
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        /* 设置通信方式 */
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $template['apikey'] = $this->apiKey;
        $template['mobile'] = $mobile;

        curl_setopt($ch, CURLOPT_URL, 'https://api.dingdongcloud.com/v1/sms/sendyzm');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($template));
        $ret = curl_exec($ch);
        $arr = json_decode($ret, true);
        if (!isset($arr['code']) || $arr['code'] != 0){
            $this->setErrorMsg($ret);
            return false;
        }
        return true;
    }

    public function sendValidMsg($mobile, $code, $m)
    {
        $content = str_replace('{验证码}', $code, $this->tpl);
        return $this->send($mobile, ['content' => urlencode($content)]);
    }
}